module OrderConcern
  extend ActiveSupport::Concern

  def sign(params={})
    key = params.delete(:key)
    query = params.sort.map do |k, v|
      "#{k}=#{v}" if v.blank?
    end.compact.join('&')
    Digest::MD5.hexdigest("#{query}&key=#{key}").upcase
  end

  def verify?(params)
    params = params.dup
    sign = params.delete('sign') || params.delete(:sign)
    sign(params) == sign
  end

  def create_wx_pay(params)
    url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
    sign_params = params.merge({appid: WxPay.appid, mch_id: WxPay.mch_id, key: WxPay.key, nonce_str: SecureRandom.uuid.tr('-', '')})
    sign_result = sign(sign_params)
    payload = "<xml>#{sign_params.map { |k, v| "<#{k}>#{v}</#{k}>" }.join}<sign>#{sign_result}</sign></xml>"
    result = RestClient::Request.execute(
        {
            method: :post,
            url: url,
            payload: payload,
            headers: {content_type: 'application/xml'}
        }.merge(WxPay.extra_rest_client_options)
    )
    Hash.from_xml(result)
  end
end